package com.jl.commons.Exception;

import com.alibaba.fastjson.JSON;
import com.jl.commons.constant.ErrorCode;
import com.jl.commons.constant.ErrorMessage;
import com.jl.commons.result.ResultData;
import com.jl.commons.utils.WebUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 全局异常处理类
 */
@ControllerAdvice
public class GlobealExceptionHandler {


    //@ExceptionHandler(value = Throwable.class)
//    @ExceptionHandler(value = Exception.class)
//    public ModelAndView defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Throwable ex) {
//        PrintWriter writer = null;
//        try {
//            if (!WebUtils.isAjax(request)) {
//                ModelAndView mav = new ModelAndView();
//                mav.addObject("exception", ex);
//                mav.addObject("url", request.getRequestURL());
//                mav.setViewName("/common/error/500");
//                return mav;
//            } else {
//                // 如果是ajax请求，JSON格式返回
//                response.setContentType("application/json;charset=UTF-8");
//                writer = response.getWriter();
//                ResultData errorResult = new ResultData();
//                errorResult.setSuccess(false);
//                errorResult.setErrorCode(ErrorCode.ERROR);
//                errorResult.setErrorMsg(ex.getMessage());
//                writer.write(JSON.toJSONString(errorResult));
//                writer.flush();
//                writer.close();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }finally {
//            //保存错误日志
//            if(writer!=null){
//                writer.close();
//            }
//        }
//        return null;
//    }


    @ExceptionHandler(UnauthorizedException.class)
    @ResponseBody
    public ResultData exceptionHandler(HttpServletRequest request,UnauthorizedException e, HttpServletResponse response) {
//        String requestUrl = request.getServletPath();
//        String a = request.getContextPath();
//        String b = request.getMethod();
//        String c = request.getScheme();
//        String d = request.getServerName();
//        String f = request.getQueryString();
//        String g = request.getLocalAddr();
//        String h = request.getLocalName();


        ResultData errorResult = new ResultData();
        errorResult.setSuccess(false);
        errorResult.setErrorCode(ErrorCode.NO_PERMISSION_ACCESS);
        errorResult.setErrorMsg(ErrorMessage.NO_PERMISSION_ACCESS);
        return errorResult;
    }

}
